<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		*{
			padding:0;
			margin:0;
		}
		#box{
			width: 600px;
			height: 500px;
			border:5px solid black;
			position: relative;
			margin:50px auto 0;
		}
		#ball{
			width: 50px;
			height: 50px;
			background: red;
			border-radius: 50%;
			position: absolute;
			top:0;
			left: 0;

		}
	</style>
</head>
<body>
	<div id="box">
		<div id="ball"></div>
	</div>
	<button id="play">play</button>
	<button id="pause">pause</button>

</body>
</html>
<script>
	/*function f(){
		return function(a, b){
			return a + b;
		};
	}
	console.log(f()(5, 6));*/

	//获取ball元素
	var ballDiv = document.getElementById("ball");

	var playBtn = document.getElementById("play");
	var pauseBtn = document.getElementById("pause");
	//记录初始位置
	var left = 0;
	var t = 0;

	var timerID;
     
     //标记x的运动方向
     var flagX = true;

     //标记y的运动方向
     var flagY = true;

	function changeX() {
	    left += flagX ? 2 : -2;
	    //修改小球的位置
	    ballDiv.style.left = left + "px";

	    //碰到右边或左边改变方向
	    if(left == 550 || left == 0){
	    	flagX = !flagX;
	    	ballDiv.style.backgroundColor = randomColor();
	    }
	   /* if(left == 550){
	    	flagX = false;
	    }
	    if(left == 0){
	    	flagX = true;
         ballDiv.style.backgroundColor = randomColor();
	    }*/	
	}

	function changeY(){
		t += flagY ? 10 : -10;
		ballDiv.style.top = t + "px";
		if(t == 0 || t == 450){
			flagY = !flagY;
			ballDiv.style.backgroundColor = randomColor();
		}
		/*if(left == 450){
	    	flagY = false;
	    }
	    if(left == 0){
	    	flagY = true;
	    	ballDiv.style.backgroundColor = randomColor();
	    }*/	

	}

	//按钮点击事件
	playBtn.onclick = function(){
		clearInterval(timerID);
		timerID = setInterval(function(){
			changeX();
			changeY();
		},20);
	}
	pauseBtn.onclick = function(){
		clearInterval(timerID);
	};

	function randomColor(){
		var r = Math.floor(Math.random() * 256);
		var g = Math.floor(Math.random() * 256);
		var b = Math.floor(Math.random() * 256);
		return "rgb(" + r + "," + g + "," + b + ")";
	}
</script>